package com.example.seckilldemo.controller;

import com.example.seckilldemo.pojo.User;

import com.example.seckilldemo.service.IGoodsService;
import com.example.seckilldemo.service.IUserService;
//import com.example.seckilldemo.vo.DetailVo;
import com.example.seckilldemo.vo.DetailVo;
import com.example.seckilldemo.vo.GoodsVo;
import com.example.seckilldemo.vo.RespBean;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ServerWebExchange;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;
import org.thymeleaf.web.servlet.JakartaServletWebApplication;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @description: 商品相关
 */

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * @description: 跳转到商品列表页面 5000*3
     * Windows 优化前 QPS：1709
     *         缓存页面 QPS：2742
     *
     * @param:
     * @return:
     */
//    @RequestMapping("/toList")
//    public String toList(Model model, HttpServletRequest request, HttpServletResponse response, @CookieValue("userTicket") String ticket) {
    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
//        if (StringUtils.isEmpty(ticket)) {
//            return "login";
//        }
////        User u = (User) session.getAttribute(ticket);
//        User u = userService.getUserByCookie(ticket, request, response);
//        if(u == null){
//            return "login";
//        }
        // Redis中获取页面，如果不为空，则直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodVo());
//        return "goodsList";
        //但是如果Redis获取页面为空的话，则手动渲染，并且存入Redis中并返回。
        var application = JakartaServletWebApplication.buildApplication(request.getServletContext());
        var exchange = application.buildExchange(request, response);
        WebContext context = new WebContext(exchange,
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);

        //并将手动渲染好的页面放置Redis缓存中
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
        }
        return html;
    }

//    @RequestMapping("/toDetail/{goodsId}")
    @RequestMapping(value = "/toDetail2/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail2(Model model, User user, HttpServletRequest request, HttpServletResponse response,
                           @PathVariable Long goodsId) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail: " + goodsId);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        int secKillStatus = 0;
        int remainSeconds = 0;
        //秒杀还未开始
        if (nowDate.before(startDate)) {
            //初始值已经是0了
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        }
        else if (nowDate.after(endDate)) {
            secKillStatus = 2;
            remainSeconds = -1;
        }
        else {
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("goods", goodsVo);
        var application = JakartaServletWebApplication.buildApplication(request.getServletContext());
        var exchange = application.buildExchange(request, response);
        WebContext context = new WebContext(exchange,
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
        if (!StringUtils.isEmpty(html)) {
            valueOperations.set("goodsDetail:" +goodsId, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public RespBean toDetail(Model model, User user, @PathVariable Long goodsId) {

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        int secKillStatus = 0;
        int remainSeconds = 0;
        //秒杀还未开始
        if (nowDate.before(startDate)) {
            //初始值已经是0了
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        }
        else if (nowDate.after(endDate)) {
            secKillStatus = 2;
            remainSeconds = -1;
        }
        else {
            secKillStatus = 1;
            remainSeconds = 0;
        }
        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setSecKillStatus(secKillStatus);
        detailVo.setRemainSeconds(remainSeconds);
        return RespBean.success(detailVo);
    }

    //@RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    //@ResponseBody
//    public String toList(Model model, User user,HttpServletRequest request, HttpServletResponse response){
//        // Redis中获取页面，如果不为空，则直接返回页面
//        //ValueOperations valueOperations = redisTemplate.opsForValue();
//        //String html = (String) valueOperations.get("goodsList");
//        //if(!StringUtils.isEmpty(html)){
//        //    return html;
//        //}
//        // 但是如果Redis获取页面为空的话，则手动渲染，并且存入Redis中并返回。
//        //WebContext context = new WebContext(   , request.getLocale(), model.asMap());
//        //html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
//
//        // 并将手动渲染好的页面放置Redis缓存中
//        //if(!StringUtils.isEmpty(html)){
//        //    valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
//        //}
//        //return html;
//
//        model.addAttribute("user", user);
//        model.addAttribute("goodsList", goodsService.findGoodVo());
//        return "goodsList";
//    }

//    @RequestMapping("/toDetail2/{goodsId}")
//    public String toDetail2(Model model, User user, @PathVariable Long goodsId){
//        model.addAttribute("user", user);
//        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//
//        Date startDate = goodsVo.getStartDate();
//        Date endDate = goodsVo.getEndDate();
//        Date nowDate = new Date();
//
//        // 秒杀状态码
//        int secKillStatus = 0;
//        // 秒杀倒计时
//        int remainSeconds = 0;
//
//        // 秒杀未开始（包含倒计时）
//        if(nowDate.before(startDate)){
//            remainSeconds = (int)((startDate.getTime() - nowDate.getTime())/1000);
//        }
//        // 秒杀已结束
//        else if(nowDate.after(endDate)){
//            secKillStatus = 2;
//            remainSeconds = -1;
//        }
//        // 秒杀进行中
//        else{
//            secKillStatus = 1;
//            remainSeconds = 0;
//        }
//        model.addAttribute("remainSeconds",remainSeconds);
//        model.addAttribute("secKillStatus", secKillStatus);
//        model.addAttribute("goods", goodsVo);
//        return "goodsDetail";
//    }
//
//
//    @RequestMapping("/detail/{goodsId}")
//    @ResponseBody
//    public RespBean toDetail(User user, @PathVariable Long goodsId){
//
//        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//        Date startDate = goodsVo.getStartDate();
//        Date endDate = goodsVo.getEndDate();
//        Date nowDate = new Date();
//        // 秒杀状态码
//        int secKillStatus = 0;
//        // 秒杀倒计时
//        int remainSeconds = 0;
//        // 秒杀未开始（包含倒计时）
//        if(nowDate.before(startDate)){
//            remainSeconds = (int)((startDate.getTime() - nowDate.getTime())/1000);
//        }
//        // 秒杀已结束
//        else if(nowDate.after(endDate)){
//            secKillStatus = 2;
//            remainSeconds = -1;
//        }
//        // 秒杀进行中
//        else{
//            secKillStatus = 1;
//            remainSeconds = 0;
//        }
//        DetailVo detailVo = new DetailVo();
//        detailVo.setUser(user);
//        detailVo.setGoodsVo(goodsVo);
//        detailVo.setRemainSeconds(remainSeconds);
//        detailVo.setSecKillStatus(secKillStatus);
//        return RespBean.success(detailVo);
//    }
}
